<?php

namespace App\Jobs\Remind;

use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

/**
 * 获取次日考勤通知数据
 *
 * Date: 2018/6/2
 * @author George
 * @package App\Jobs\Remind
 */
class AttendanceRemind implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

	/**
	 * 获取次日的通知
	 *
	 * Date: 2018/6/1
	 * @author George
	 */
    public function handle()
    {
		$timestamp = strtotime('+1 day');
		$date = date('Y-m-d', $timestamp);
		DB::table('schedules')->select([
			'schedules.id',
			'users.id as user_id',
			'schedules.start_timestamp',
			'schedules.end_timestamp'
		])->leftJoin('users', 'schedules.user_id', '=', 'users.id')
			->whereDate('date', $date)
			->where('users.attendance_remind', 1)
			->orderBy('id')
			->chunk(2000, function ($schedules) {
				foreach ($schedules as $schedule) {
					Redis::connection('remind')->hset("signin_" . substr($schedule->start_timestamp, 0, 16), $schedule->id, "user_{$schedule->user_id}");
					Redis::connection('remind')->hset("signout_" . substr($schedule->end_timestamp, 0, 16), $schedule->id, "user_{$schedule->user_id}");
				}
			});
		Log::info(date('Y-m-d H:i:s') . '已将待推送的任务添加到Hash表中');
    }
}
